package com.gaga.common.utils;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.Bead;
import net.beadsproject.beads.core.UGen;
import net.beadsproject.beads.core.io.JavaSoundAudioIO;
import net.beadsproject.beads.data.Sample;
import net.beadsproject.beads.ugens.BiquadFilter;
import net.beadsproject.beads.ugens.Gain;
import net.beadsproject.beads.ugens.SamplePlayer;
import net.beadsproject.beads.ugens.Static;

import javax.sound.sampled.Mixer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liujia
 * @version 1.0
 * @date 2025/3/30-15:32
 */
public class AudioPlayerUtils20505 {

    /**
     * 播放完成回调方法
     */
    private Runnable onPlaybackFinished;
    private AudioContext ac;
    private SamplePlayer player;

    private Gain masterGain;

    private List<BiquadFilter> filters = new ArrayList<>();

    private static volatile boolean isCompleted = false;

    // 8个频段的中心频率（与UI对应）
    public static final float[] FREQUENCIES = {
            115, 240, 455, 800, 2000, 4500, 9000
    };

    // 新增成员变量
    private boolean isPaused = false;
    private float currentSpeedFactor = 1.0f;
    private float currentVolumeFactor = 1.0f;
    private double pausePosition = 0;

    // 新增设备选择相关成员变量
    private JavaSoundAudioIO audioIO;

    /**
     * 添加完成回调方法
     */
    public void setOnPlaybackFinished(Runnable callback) {
        this.onPlaybackFinished = callback;
    }

    /**
     * 初始化音频设备（兼容变速）
     *
     * @param filePath
     * @param deviceName
     */
    public void init(String filePath, String deviceName) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            Mixer.Info targetMixerInfo = DeviceInfoUtils.getTargetAudioDevice(deviceName, true);
            if (targetMixerInfo == null) {
                throw new IllegalArgumentException("设备未找到: " + deviceName);
            }
            isCompleted = false;
            filters = new ArrayList<>();
            // 初始化音频设备选择
            audioIO = new JavaSoundAudioIO(512);
            audioIO.selectMixer(DeviceInfoUtils.getMixerIndex(deviceName));
            // 使用配置好的音频IO
            ac = new AudioContext(audioIO);
            // 加载音频
            Sample sample = new Sample(filePath);
            player = new SamplePlayer(ac, sample);
            player.setLoopType(SamplePlayer.LoopType.NO_LOOP_FORWARDS);

            player.setEndListener(new Bead() {
                @Override
                protected void messageReceived(Bead message) {
                    if (!isCompleted) {
                        isCompleted = true;
                        System.out.println("音频播放完成！");
                        if (onPlaybackFinished != null) {
                            // 触发回调
                            onPlaybackFinished.run();
                        }
                    }
                }
            });

            // 初始化8段滤波器
            createFilters();
            // 创建主音量控制
            masterGain = new Gain(ac, 2, 1.0f);

            // 构建音频链：播放器 -> 各滤波器并联 -> 主音量 -> 输出
            UGen lastNode = player;
            for (BiquadFilter filter : filters) {
                filter.addInput(lastNode);
                lastNode = filter;
            }
            masterGain.addInput(lastNode);
            ac.out.addInput(masterGain);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void createFilters() {
        for (float freq : FREQUENCIES) {
            BiquadFilter filter = new BiquadFilter(ac, 2, BiquadFilter.Type.PEAKING_EQ);
            filter.setFrequency(freq)
                    .setQ(1.0f)    // Q值可根据需求调整
                    .setGain(0.0f); // 默认增益0dB
            filters.add(filter);
        }
    }

    // 设置指定频段的增益（bandIndex: 0-6）
    public void setBandGain(int bandIndex, float gainDB) {
        if (bandIndex >= 0 && bandIndex < filters.size()) {
            filters.get(bandIndex).setGain(gainDB);
        }
    }


    /**
     * 播放
     */
    public void play() {
        if (isPaused) {
            // 恢复播放：从暂停位置继续
            setSpeed(currentSpeedFactor);
            setVolume(currentVolumeFactor);
            player.setPosition(pausePosition);
            isPaused = false;
        } else if (player != null) {
            // 全新播放
            ac.start();
        }
    }


    /**
     * 停止
     */
    public void stop() {
        if (ac != null) {
            ac.stop();
            isPaused = false;
            pausePosition = 0;
            if (player != null) {
                // 重置播放位置
                player.setPosition(0);
            }
        }
    }

    /**
     * 暂停播放（保留播放位置）
     */
    public void pause() {
        if (player != null && ac != null && ac.isRunning()) {
            // 记录当前播放位置和速度
            pausePosition = player.getPosition();
            currentSpeedFactor = player.getRateUGen().getValue();
            currentVolumeFactor = masterGain.getGain();
            // 设置速率为0实现暂停
            setSpeed(0f);
            setVolume(0f);
            isPaused = true;
        }
    }

    /**
     * 设置音量
     */
    public void setVolume(float volume) {
        masterGain.setGain(volume);
    }

    public void setSpeed(float factor) {
        UGen rateuGen = new Static(ac, Math.max(0.5f, Math.min(2.0f, factor)));
        player.setRate(rateuGen);
    }


    public static void main(String[] args) throws Exception {

        AudioPlayerUtils20505 player = new AudioPlayerUtils20505();
        player.init("C:/Users/lenovo/Desktop/test/1.wav", "耳机");
        // 播放 这个播放速度需要修改
//        player.setSpeed(2f);
        player.setVolume(1f);
        player.play();
        Thread.sleep(3000);
        player.pause();
        Thread.sleep(2000);
        player.play();
    }

}
